package com.tjec.project.projectWorkbench.controller;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.Constants;
import com.tjec.common.constant.ProjectStatus;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.PageDomain;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.service.IBmsBusinessService;
import com.tjec.project.mdmSynchronous.domain.BmsProjectLeader;
import com.tjec.project.mdmSynchronous.service.IBmsProjectLeaderService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsMdExpertType;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectFocus;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.domain.BmsProjectSimple;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.projectWorkbench.service.IBmsProjectContractService;
import com.tjec.project.projectWorkbench.service.IBmsProjectFocusService;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.BmsMdArea;
import com.tjec.project.system.domain.SysRole;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.domain.vo.BmsAttachmentVo;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.IBmsMdAreaService;
import com.tjec.project.system.service.ISysRoleService;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 项目（项目概况）Controller
 *
 * @author tjec
 * @date 2020-04-14
 */
@Api(value = "项目（项目概况）" , tags = {"项目/项目概况接口"})
@RestController
@RequestMapping("/project/info")
public class BmsProjectController extends BaseController {

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private IBmsProjectMemberService projectMemberService;

    @Autowired
    private IBmsBusinessService bmsBusinessService;

    @Autowired
    private IBmsMdAreaService bmsMdAreaService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBmsProjectFocusService bmsProjectFocusService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBmsProjectContractService bmsProjectContractService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private BmsProjectMapper bmsProjectMapper;

    @Autowired
    private IBmsAttachmentService bmsAttachmentService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;
    @Value("${EC.account}")
    private String account;

    /**
     * 项目清单管理列表
     */
    @ApiOperation("项目负责人工作台-项目清单管理列表")
//    @PreAuthorize("@ss.hasPermi('project:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsProject bmsProject) {
        //项目状态为作废
       /* if(StringUtils.isNotBlank(bmsProject.getStatus())&&bmsProject.getStatus().equals(ProjectStatus.cancellation)){
            bmsProject.setIsvalid("0");
            bmsProject.setStatus("");
        }*/        String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsProject.getProjectLeader());

        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsProject.setProjectLeaderNo(projectLeaderNo);
            bmsProject.setProjectLeader("");
        }
        startPage();
        //负责人工作台不显示"作废"项目，不显示“冻结”项目
        bmsProject.setIsvalid("1");
        bmsProject.setFreezeStatus("1");
        List<BmsProject> list = bmsProjectService.selectBmsProjectList(bmsProject);
        return getDataTable(list);
    }

    /**
     * 项目工作台-项目一览列表
     */
    @ApiOperation("项目工作台-项目一览列表")
//    @PreAuthorize("@ss.hasPermi('project:info:projectGlanceList')")
    @GetMapping("/projectGlanceList")
    public TableDataInfo projectGlanceList(BmsProject bmsProject) {
        String currentUserId = SecurityUtils.getLoginUser().getUser().getUserId();
        //判断用户是否为管理员
        if(SecurityUtils.isAdmin(currentUserId) || account.equals(SecurityUtils.getLoginUser().getUser().getUserName())){
            bmsProject.setUserId(null);
        }else{
            if(StringUtils.isBlank(bmsProject.getUserId())){
                bmsProject.setUserId(currentUserId);
            }
        }
        /*//项目状态为作废
        if(StringUtils.isNotBlank(bmsProject.getStatus())&&bmsProject.getStatus().equals(ProjectStatus.cancellation)){
            bmsProject.setIsvalid("0");
            bmsProject.setStatus("");
        }*/
        String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(bmsProject.getUserId());
        if(StringUtils.isNotBlank(projectLeaderNo)){
            bmsProject.setProjectLeaderNo(projectLeaderNo);
        }
        startPage();
        //项目工作台不显示"作废"项目，不显示“冻结”项目
        bmsProject.setIsvalid("1");
        bmsProject.setFreezeStatus("1");
        List<BmsProjectSimple> list = bmsProjectService.selectBmsProjectGlanceList(bmsProject);
        for (BmsProjectSimple project : list) {
            BmsProjectMember bmsProjectMember = new BmsProjectMember();
            bmsProjectMember.setProjectId(project.getGuid());
            Integer personnelNo = projectMemberService.countBmsProjectMemberNo(bmsProjectMember);
            project.setPersonnelNo(personnelNo);
            //是否关注项目
            BmsProjectFocus bmsProjectFocus = new BmsProjectFocus();
            bmsProjectFocus.setProjectId(project.getGuid());
            bmsProjectFocus.setUserId(currentUserId);
            Set<BmsProjectFocus> bmsProjectFocuss = bmsProjectFocusService.selectBmsProjectFocusList(bmsProjectFocus);
            if(!CollectionUtils.isEmpty(bmsProjectFocuss)){
                project.setIsFocus(1);
            }else{
                project.setIsFocus(0);
            }
            //业务数
            project.setBusinessCount(bmsBusinessService.getBusinessCount(project.getGuid()));
        }
        return getDataTable(list);
    }

    /**
     * 根据项目负责人同步经营系统的项目数据
     */
    @ApiOperation("项目同步(根据项目负责人同步经营系统的项目数据)")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:synchronous')")
    @GetMapping(value = "/synchronous/{userGuid}")
    public AjaxResult synchronous(@PathVariable String userGuid) {
//        String userGuid = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId();
        if(StringUtils.isBlank(userGuid)){
            return AjaxResult.error("同步项目负责人userId为空");
        }
        bmsProjectService.updateBmsProjectByThirdParty(userGuid, false,true);
        bmsProjectService.updateBmsProjectContractByThirdParty(userGuid);
        return AjaxResult.success();
    }

    /**
     * 编辑项目概况（项目启动）
     */
    @ApiOperation("编辑项目概况/项目启动")
    @ApiImplicitParam(name = "bmsProject", value = "编辑项目概况/项目启动", dataType = "BmsProject")
    @Log(title = "项目概况", businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('project:info:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody BmsProject bmsProject) {
        return toAjax(bmsProjectService.updateBmsProject(bmsProject));
    }

    /**
     * 获取项目详细信息
     */
    @ApiOperation("获取项目详细信息（项目概况）")
    @ApiImplicitParam(name = "guid", value = "项目guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('project:info:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid) {
        BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(guid);

        //查询此人是否是当前项目成员或项目负责人
      int checkRes = bmsProjectService.checkUserIsMember(guid,tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId(),tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getJobNo());
      if(checkRes>0) {
    	  bmsProject.setIsMember("1");
      }else {
    	  bmsProject.setIsMember("0");
      }

        if (null != bmsProject) {
            String link = bmsProject.getLink();
            List<Map<String, Object>> linkList = new ArrayList<>();
            if (StringUtils.isNotBlank(link)) {
                String[] strLink = link.split(";");
                for (String str : strLink) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("linkName", str.split(",")[0]);
                    map.put("linkUrl", str.split(",")[1]);
                    linkList.add(map);
                }
                bmsProject.setLinkArray(linkList);
            }
            if(StringUtils.isNotBlank(bmsProject.getArea())){
                String[] areas = bmsProject.getArea().split(";");
                bmsProject.setAreas(areas);
               List<BmsMdArea> bmsMdAreas = bmsMdAreaService.selectBmsMdAreaByGuids(areas);
                String areaName = "";
                if(!CollectionUtils.isEmpty(bmsMdAreas)){
                    for (int i = 0; i < bmsMdAreas.size(); i++) {
                        if(i == bmsMdAreas.size()-1){
                            areaName += bmsMdAreas.get(i).getCname();
                        }else{
                            areaName += bmsMdAreas.get(i).getCname()+" / ";
                        }
                    }
                }
                bmsProject.setAreaName(areaName);
            }
            if(StringUtils.isNotBlank(bmsProject.getIndustry())){
                String[] industrys = bmsProject.getIndustry().split(";");
                bmsProject.setIndustrys(industrys);
            }
            //获取该项目所有业务名称并去重
            BmsBusiness bmsBusiness = new BmsBusiness();
            bmsBusiness.setProjectId(bmsProject.getGuid());
            List<BmsBusiness> list = bmsBusinessService.selectBmsBusinessList(bmsBusiness);
            Set<String> businessCategory = new HashSet<>();
            for (BmsBusiness business : list) {
                businessCategory.add(business.getMenuName());
            }
            bmsProject.setBusinessCategory(StringUtils.strip(businessCategory.toString(), "[]"));
            if(bmsProject.getBusinessCategory()==null || "null".equals(bmsProject.getBusinessCategory())) {
            	bmsProject.setBusinessCategory("");
            }
            if(!CollectionUtils.isEmpty(bmsProject.getBmsAttachments())){
                for (BmsAttachment bmsAttachment : bmsProject.getBmsAttachments()) {
                    bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                }
            }
            if(StringUtils.isNotBlank(bmsProject.getShowProjectMain())) {
            	BmsAttachment att = bmsAttachmentService.selectBmsAttachmentByGuid(bmsProject.getShowProjectMain());
            	if(att!=null && StringUtils.isNotBlank(att.getStoragePath())) {
            		att.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + att.getStoragePath());
            	}
            	bmsProject.setProjectMain(att);
            }
            if(StringUtils.isNotBlank(bmsProject.getAtts())) {
            	bmsProject.setProjectAttIds(Arrays.asList(bmsProject.getAtts().split(",")));
            	List<BmsAttachmentVo> resAtts = bmsAttachmentService.selectBmsAttachmentDownload(bmsProject.getAtts().split(","));
            	if(resAtts!=null && resAtts.size()>0) {
            		for (BmsAttachmentVo bmsAttachment : resAtts) {
                        bmsAttachment.setStoragePath(http + ip +Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                    }
            	}
            	bmsProject.setProjectAtts(resAtts);

            }

        }
        return AjaxResult.success(bmsProject);
    }

    /**
     * 首页-我关注的项目
     * liuxu
     */
    @ApiOperation("首页-我关注的项目")
    @GetMapping("/focusProject")
    public AjaxResult focusProject() {
        BmsProjectFocus bmsProjectFocus = new BmsProjectFocus();
        bmsProjectFocus.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        return AjaxResult.success(bmsProjectFocusService.selectBmsProjectFocusList(bmsProjectFocus));
    }

    /**
     * 首页-我的项目
     */
    @ApiOperation("首页-我的项目")
    @GetMapping("/myProject")
    public AjaxResult myProject(){
        return AjaxResult.success(bmsProjectService.countMyProject(SecurityUtils.getLoginUser().getUser().getUserId()));
    }

    /**
     * 是否为项目成员(如果该用户为项目负责人角色)
     */
    @ApiOperation("是否为项目成员")
    @GetMapping("/isProjectMembers")
    public AjaxResult isManager(BmsProjectMember bmsProjectMember){
        boolean isProjectMembers;
        if(StringUtils.isBlank(bmsProjectMember.getProjectId())){
            return AjaxResult.error();
        }
        if(StringUtils.isBlank(bmsProjectMember.getUserId())){
            bmsProjectMember.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        }
        //判断当前用户是否包含项目负责人角色
        if(sysRoleService.isExistRoleByUserId(Constants.ROLE_PROJECT_LEADER_KEY, bmsProjectMember.getUserId())){
            isProjectMembers = false;
        }else{
            bmsProjectMember.setRole(NumCode.ONE.getCode());
            List<BmsProjectMember> list = projectMemberService.selectBmsProjectMemberList(bmsProjectMember);
            isProjectMembers = CollectionUtils.isEmpty(list)?false:true;
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("isProjectMembers",isProjectMembers);
        return ajaxResult;
    }

    /**
     * 是否为项目负责人
     */
    @ApiOperation("是否为项目负责人")
    @GetMapping("/isProjectLeader")
    public AjaxResult isProjectLeader(String leader){
        boolean isProjectLeader = false;
        String userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //判断当前用户是否包含项目负责人角色
        if(leader.equals(userId)&&sysRoleService.isExistRoleByUserId(Constants.ROLE_PROJECT_LEADER_KEY, userId)){
            isProjectLeader = true;
        }
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("isProjectLeader",isProjectLeader);
        return ajaxResult;
    }

    /**
     * 根据项目同步经营系统的项目和项目合同数据
     */
    @Transactional
    @ApiOperation("根据项目同步经营系统的项目和项目合同数据")
//    @PreAuthorize("@ss.hasPermi('projectleader:personnel:synchronous')")
    @GetMapping(value = "/projectSynchronous/{projectId}")
    public AjaxResult projectSynchronous(@PathVariable String projectId) {
        if(StringUtils.isBlank(projectId)){
            return AjaxResult.error("同步项目projectId为空");
        }
        BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(projectId);
        if(bmsProject==null){
            return AjaxResult.error("项目不存在");
        }
        //强制更新默认设置为0，上线恢复取最大值
//        bmsProjectContractService.synchronous(bmsProject.getCode(),bmsProjectContractService.selectMaxTime());
        bmsProjectService.updateBmsProjectByThirdParty(bmsProject);
        bmsProjectContractService.synchronous(bmsProject.getCode(), bmsProjectContractService.selectMaxTime());
        return AjaxResult.success();
    }

    @GetMapping(value = "/checkProjectStatus/{projectId}")
    public AjaxResult checkProjectStatus(@PathVariable String projectId) {
    	return AjaxResult.success(bmsProjectService.checkProjectStatus(projectId));
    }

}
